namespace :sync_osp_relative_memos_num do
  task :start => :environment do
    while true
      batch_size = 1000
      unless SolrIncrementalIndexCursor.where(name: 'OpenSourceProjectForSyncNum').exists?
        rm2osp_new_cursor=SolrIncrementalIndexCursor.new(name: 'OpenSourceProjectForSyncNum', cursor: 0)
        rm2osp_new_cursor.save
      end

      cur_id = 0
      rm2osp_cursor=SolrIncrementalIndexCursor.where(name: 'OpenSourceProjectForSyncNum').last
      cur_id = rm2osp_cursor.cursor
      puts(cur_id)


      begin
        max_id = OpenSourceProject.maximum(:id)
        puts("max: "+max_id.to_s)
        #Thread.new do
        while cur_id < max_id do
          begin
            OpenSourceProject.where("id > #{cur_id} AND id < #{cur_id+batch_size}").each do |osp|
              #puts('start')
              RelativeMemoToOpenSourceProject.set_table_name RelativeMemoToOpenSourceProject.getTableName osp.id
              table_name = RelativeMemoToOpenSourceProject.getTableName osp.id
              sql = "select id AS num FROM " + table_name + " where osp_id = ?"
              num = (RelativeMemoToOpenSourceProject.find_by_sql [sql, osp.id]).count
              osp.update_attribute('relative_memos_num', num)
              cur_id=osp.id
              puts("OpenSourceProject: "+cur_id.to_s)
              #puts('inside')
            end
            rm2osp_cursor.update_attribute('cursor', cur_id)

          rescue Exception => e
            puts e
          end
        end

      rescue Exception => e
        puts e
      end

      sleep(60)

      # end
    end
  end
end
